<template>
    <div class="senior-search">
        <home-banner home></home-banner>
        <div class="senior-card">
            <div class="search-form">
                <el-form :model="form" ref="searchForm" :rules="rules" label-width="80px">
                    <div class="search-inputs">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入姓名" />
                        </el-form-item>
                        <el-form-item label="学号" prop="stuId">
                            <el-input v-model="form.stuId" placeholder="请输入学号" />
                        </el-form-item>
                        <el-form-item label="专业">
                            <el-select
                                v-model="form.major"
                                clearable
                                placeholder="请选择专业"
                                :loading="majorLoading"
                                @click="handleGetMajors"
                                @change="
                                    () => {
                                        classLoading = true
                                        form.class = ''
                                        form.name = ''
                                    }
                                "
                            >
                                <el-option v-for="item in majors" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="班级">
                            <el-select
                                v-model="form.class"
                                clearable
                                placeholder="请选择班级"
                                :loading="classLoading"
                                @click="handleGetClasses"
                            >
                                <el-option v-for="item in classes" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
                <div class="search-btn">
                    <el-form-item>
                        <el-button type="primary" @click="submitForm" :loading="searchLoading" style="width: 100px">
                            {{ searchLoading ? '加载中' : '搜索' }}
                        </el-button>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="handleExport" style="width: 100px; margin-left: 10px">
                        导出
                    </el-button>
                </el-form-item>
            </div>
            <div class="search-result">
                <el-table
                    :data="tableData"
                    ref="table"
                    :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }"
                    height="450"
                    empty-text="暂无数据"
                    :loading="isLoading"
                    @row-click="searchStudent"
                    :row-style="handleHover"
                    @cell-mouse-enter="handleMouseEnter"
                >
                    <el-table-column prop="name" label="姓名" />
                    <el-table-column prop="stuId" label="学号" />
                    <el-table-column prop="major" label="专业" />
                    <el-table-column prop="cls" label="班级" />
                    <el-table-column prop="grade" label="类型" />
                </el-table>
            </div>
            <div class="pagination-block" v-if="showPaginationBlock">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :page-size="10"
                    @current-change="handlePageChange"
                    :disabled="searchLoading"
                />
            </div>
        </div>
        <div style="height: 50px"></div>
    </div>
</template>

<script>
import { reactive, ref, onMounted, watch } from 'vue'
import api, { getStudents } from '@/api/student'
import HomeBanner from '@/components/common/HomeBanner'
import { useRouter } from 'vue-router'
import { ElLoading } from 'element-plus'

export default {
    props: ['keyword'],
    components: {
        HomeBanner,
    },
    setup(props) {
        const form = reactive({
            page: 1,
            size: 10,
            name: '',
            stuId: '',
            major: '',
            class: '',
        })

        const rules = reactive({
            name: [
                {
                    pattern: /^[a-zA-Z\u4e00-\u9fa5\s]*$/,
                    message: '请输入中文或英文',
                    trigger: 'blur',
                },
                {
                    max: 20,
                    message: '长度在 20 字以内',
                    trigger: 'blur',
                },
            ],
            stuId: [
                {
                    pattern: /^[a-zA-Z0-9]*$/,
                    message: '请输入数字或英文',
                    trigger: 'blur',
                },
                {
                    min: 0,
                    max: 12,
                    message: '长度在 12 个字以内',
                    trigger: 'blur',
                },
            ],
            major: [
                {
                    min: 0,
                    max: 30,
                    message: '长度在 30 个字符以内',
                    trigger: 'change',
                },
            ],
            class: [
                {
                    min: 0,
                    max: 30,
                    message: '长度在 30 个字符以内',
                    trigger: 'change',
                },
            ],
        })

        const tableData = reactive([])
        const searchForm = ref(null)
        const searchLoading = ref(false)
        const showPaginationBlock = ref(false)
        const total = ref(0)
        const keyword = ref('')
        const isLoading = ref(false)
        const currentRow = ref(null)

        const validateForm = () => {
            return new Promise((resolve, reject) => {
                searchForm.value.validate((valid) => {
                    if (valid) {
                        resolve()
                    } else {
                        reject('表单验证失败！')
                    }
                })
            })
        }

        const submitForm = async () => {
            try {
                await validateForm()
                searchLoading.value = true
                isLoading.value = true

                await handleSearch()
                showPaginationBlock.value = true
            } catch (error) {
                console.log('error submit!', error)
            } finally {
                searchLoading.value = false
                isLoading.value = false
                form.page = 1
            }
        }

        const handleSearch = async () => {
            try {
                const res = await getStudents(form)
                total.value = res.data.total

                tableData.splice(0, tableData.length, ...res.data.records)
            } catch (error) {
                console.error(error)
                // alert('请求失败，请重新尝试')
            }
        }

        const handlePageChange = async (page) => {
            form.page = page
            await submitForm()
        }
        const majors = reactive([])
        let majorLoading = ref(true)
        const classes = reactive([])
        let classLoading = ref(true)

        const handleGetMajors = async () => {
            if (!majorLoading.value) return
            try {
                const res = await api.getMajors()

                majors.splice(0, majors.length, ...res.data)
                majorLoading.value = false
            } catch (error) {
                console.error(error)
                // alert('请求失败， 请重新尝试')
            }
        }

        const handleGetClasses = async () => {
            if (!classLoading.value) return
            try {
                const res = await api.getClasses(form.major)

                classes.splice(0, classes.length, ...res.data)
                classLoading.value = false
            } catch (error) {
                console.error(error)
                // alert('请求失败，请重新尝试')
            }
        }

        const handleHover = ({ row }) => {
            if (row === currentRow.value) {
                return {
                    'font-size': '18px',
                    cursor: 'pointer',
                }
            }
        }

        const handleMouseEnter = (row) => {
            currentRow.value = row
        }

        const handleExport = async () => {
            const loading = ElLoading.service({
                lock: true,
                text: '导出中...',
                // spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            try {
                let res = await api._export(form.name, form.stuId, form.major, form.class, {
                    responseType: 'arraybuffer',
                    timeout: 10000,
                })
                loading.close()
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = URL.createObjectURL(new Blob([res.data], { type: res.headers['content-type'] }))
                const download = res.headers['content-disposition'].split("=utf-8''")[1]
                link.download = decodeURI(download)
                link.click()
                URL.revokeObjectURL(link.href)
            } catch (error) {
                console.error(error)
            } finally {
                loading.close()
            }
        }

        const router = useRouter()
        const searchStudent = async (row) => {
            // console.log(row.stuId)
            await router.push({
                name: 'StudentInfoPage',
                params: {
                    id: row.stuId,
                },
            })
        }

        watch(
            () => props.keyword,
            (newValue) => {
                keyword.value = newValue
                form.name = newValue
                form.page = 1
                handleSearch()
            }
        )

        onMounted(async () => {
            if (location.search.includes('keyword=')) {
                keyword.value = decodeURIComponent(location.search.split('keyword=')[1])
            }
            if (keyword.value) {
                form.name = keyword.value
                await handleSearch()
            }
            await submitForm()
        })

        return {
            form,
            tableData,
            rules,
            validateForm,
            total,
            handleSearch,
            submitForm,
            searchForm,
            handlePageChange,
            majors,
            majorLoading,
            classes,
            classLoading,
            handleGetMajors,
            handleGetClasses,
            searchLoading,
            showPaginationBlock,
            searchStudent,
            isLoading,
            handleHover,
            handleMouseEnter,
            currentRow,
            handleExport,
        }
    },
}
</script>

<style lang="less" scoped></style>
